package emulator.sidplay;

import java.io.PrintStream;

import emulator.analyzer.sid.SidInfo;
import emulator.analyzer.sid.SidProcessor;

public class SidVicCon {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length < 3)
		{
			System.out.println("SID Vicious Converter: arguments missing.");
			System.out.println("Usage: SidVicCon <sidplay path> <SID> <target prg>");
			System.exit(0);
		}
		String player_file_name = args[0];
		String label_file_name = player_file_name.replace(".prg", ".lbl");
		String sid_file_name = args[1];
		String prg_file_name = args[2];
		
		int result = convertSid(0, 0, sid_file_name, player_file_name, label_file_name, prg_file_name, System.out, System.err);
		System.exit(result);
	}

	public static int convertSid(
			int first_song, int last_song,
			String sid_file_name,
			String player_prg_name, String player_lbl_name,
			String output_file_name, PrintStream out, PrintStream err)
	{
		boolean verbose = (output_file_name == null);
		try {
			out.println("Loading SID \""+sid_file_name+"\"");
			SidPlayPrg player = new SidPlayPrg();
			player.load(player_prg_name, player_lbl_name);
			SidProcessor sid_processor = new SidProcessor(sid_file_name, out);
			out.println("Analysing SID ...");
			if (verbose)
			{
				SidInfo sid_info = sid_processor.loadSid();
				sid_info.print(out);
			}
			if (sid_processor.processSid(first_song, last_song, verbose))
			{
				if (sid_processor.isConvertiblePrinting(out))
				{
					if (output_file_name != null)
					{
						out.println("Writing Vicious SID \""+output_file_name+"\"");
						player.setSid(sid_processor);
						player.write(output_file_name, first_song);
					}
					else
						sid_processor.printResult(out);
				}
				else
				{
					out.println("?Conversion failed.");
					return 1;
				}
			}
			else
			{
				err.println("SID analysis failed.");
				return 1;
			}
		}
		catch (Exception e)	{
			err.println("?Exception: "+e.getMessage());
			return 1;
		}
		out.println("Ready.");
		return 0;
	}
}
